package com.atguigu.spring5.dao;

import com.atguigu.spring5.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

@Repository
public class BookDaoImpl implements BookDao {

    // 注入JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 添加
    @Override
    public void add(Book book) {
        // 创建sql语句
        String sql = "insert into t_book values(?,?,?)";
        // 调用方法实现
        Object[] args = {book.getUserId(), book.getUsername(), book.getUstatus()};
        int result = jdbcTemplate.update(sql, args);
        System.out.println(result);
    }

    // 修改
    @Override
    public void update(Book book) {
        String sql = "update t_book set username=?, ustatus=? where user_id=?";
        Object[] args = {book.getUsername(), book.getUstatus(), book.getUserId()};
        int result = jdbcTemplate.update(sql, args);
        System.out.println(result);
    }

    // 删除
    @Override
    public void delete(String id) {
        String sql = "delete from t_book where user_id=?";
        int result = jdbcTemplate.update(sql, id);
        System.out.println(result);
    }

    // 查询表记录数
    @Override
    public int findCount() {
        String sql = "select count(*) from t_book";
        Integer result = jdbcTemplate.queryForObject(sql, Integer.class);
        return result;
    }

    // 根据ID查询
    @Override
    public Book findById(String id) {
        String sql = "select * from t_book where user_id=?";
        Book result = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Book.class), id);
        return result;
    }

    // 查询返回集合
    @Override
    public List<Book> findAll() {
        String sql = "select * from t_book";
        List<Book> result = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Book.class));
        return result;
    }

    // 批量添加
    @Override
    public void batchAdd(List<Object[]> batchArgs) {
        String sql = "insert into t_book values(?,?,?)";
        int[] result = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(result));
    }

    // 批量修改
    @Override
    public void batchUpdate(List<Object[]> batchArgs) {
        String sql = "update t_book set username=?, ustatus=? where user_id=?";
        int[] result = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(result));
    }

    // 批量删除
    @Override
    public void batchDelete(List<Object[]> batchArgs) {
        String sql = "delete from t_book where user_id=?";
        int[] result = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(result));
    }
}
